<?php

if (session::user() && (session::user()->hasRole('ADMIN') || session::user()->hasRole('EMAIL')))
{

   $r = array(
      'result' => false,
      'data'   => array()
   );

   switch($action)
   {
      # SAVE TEMPLATE
      case 1:
         $f = $REQUEST->dataPost('f');
         if(!empty($f['title']) && !empty($f['template']))
         {
            $sql = '`meccano_dispatch_tmpl` SET `title` = "%s", `from_name` = "%s", `from_email` = "%s", `description` = "%s", `template` = "%s"';
            $sql_vars = array(
               $f['title'],
               $f['from_name'],
               $f['from_email'],
               (!empty($f['description']) ? $f['description'] : ''),
               $f['template']
            );
            if(!empty($id))
            {
               $sql = 'UPDATE '. $sql .' WHERE `id` = %i';
               $sql_vars[] = $id;
            } else
            {
               $sql = 'INSERT INTO '. $sql;
            }

            $DB->DB_QueryBuilder($sql, $sql_vars);
            if($DB->DB_Query())
            {
               $r['result'] = true;
               $r['data']   = getTemplatesList();
            }
         }
         echo json_encode($r);
         exit();
         break;


      # DELETE TEMPLATE
      case 2:
         if(!empty($id))
         {
            $DB->sql = 'DELETE FROM `meccano_dispatch_tmpl` WHERE `id` = '. $id;
            $DB->DB_Query();
            $r['result'] = true;
            $r['data']   = getTemplatesList();
         }
         echo json_encode($r);
         exit();
         break;

      # GET AN TEMPLATE
      case 3:
         if(!empty($id))
         {
            $DB->sql = 'SELECT * FROM `meccano_dispatch_tmpl` WHERE `id` = '. $id;
            if($DB->DB_Fetch())
            {
               $r['result'] = TRUE;
               $r['data']   = reset($DB->fetched);
            }
         }
         echo json_encode($r);
         exit();
         break;
   }

   # SAVE SETTINGS
   if(request::getRequest('Last') == 'settings')
   {
      $dispatchSettings = array(
         'categories' => array()
      );
      
      if(!empty($_POST['f']['dispatch_category']))
      {
         $tmp = array();
         foreach($_POST['f']['dispatch_category'] AS $v)
         {
            if(($n = $TREE->getNode($v)))
            {
               $tmp[] = $n->id;
            }
         }
         $dispatchSettings['categories'] = array_unique($tmp);
         
      }
      
      $CF = config::getInstance();
      $CF->updateConfig('dispatch', 'settings', $dispatchSettings);
      header('location: /admin/dispatch.php');
   }
   
   
   # SEND NEW DISPATCH
   if(request::getRequest('Last') == 'send' && !empty($_POST['f']) && $id)
   {
      $usedItems = array();
      if(!empty($_POST['f']['article']))
      {
         $usedItems['article'] = $_POST['f']['article'];
      }
      dispatch::buildHtml($id, $usedItems, FALSE);
      dispatch::sendDispatch(
              (!empty($_POST['f']['subject']) ? $_POST['f']['subject'] : FALSE),
              (!empty($_POST['f']['start'])   ? $_POST['f']['start']   : FALSE),
              (!empty($_POST['f']['group'])   ? $_POST['f']['group']   : FALSE)
      );
      header('location: /admin/dispatch.php');
   }
   
   
   # GET DISPATCH TEMPLATES
   $dispatchTemplates = getTemplatesList();
   $SMARTY->assign('dispatchTemplates', $dispatchTemplates);
   $SMARTY->assign('dispatchSettings', config::read('settings', 'dispatch'));

   # NEW DISPATCH
   if(request::getRequest('Last') == 'new' && !empty($_GET['template']) && is_numeric($_GET['template']))
   {
      $template = dispatch::buildHtml($_GET['template']);
      $SMARTY->assign('templateExample', $template);
      $SMARTY->assign('templateData', dispatch::getTemplate());
      $SMARTY->assign('dGroups', $USERS->getGroups());
      $layout = 'dispatch-new.html';
   } else
   {
      $dispatchList = dispatch::getList();
      $SMARTY->assign('dispatchList', $dispatchList);
      
      $layout = 'dispatch.html';
   }
} else
{
   if (session::user())
   {
      $ErrorHandler->setError(
              array(
                  'code' => 'access',
                  'varkey' => 'access_denied'
              )
      );
   }
   $layout = 'login.html';
}






/******************************************************************************
 *                          F U N C T I O N S
 ******************************************************************************/


function getTemplatesList()
{
   $DB = database::getInstance();
   $DB->sql = 'SELECT * FROM `meccano_dispatch_tmpl` ORDER BY `title`';
   return $DB->DB_Fetch();
}


# RAM SMARTY FUNCTIONS
function ram_get_template($tpl_name, &$tpl_source, &$smarty_obj)
{
   if(!empty(dispatch::$templates[$tpl_name]))
   {
      $tpl_source = dispatch::$templates[$tpl_name];
      return TRUE;
   } else
   {
      return FALSE;
   }
}

function ram_get_timestamp($tpl_name, &$tpl_timestamp, &$smarty_obj)
{
   $tpl_timestamp = time() + 1;
   return TRUE;
}

function ram_get_secure($tpl_name, &$smarty_obj)
{
    return TRUE;
}

function ram_get_trusted($tpl_name, &$smarty_obj)
{
}